<?php
/**
 * +---------------------------------------------------
 * @File: common.php
 * @Function: 
 * @Date: 2011-6-1
 * @Author: Jackean <mosquitoyuan@163.com>
 * @Version: 
 * +---------------------------------------------------
 */

//格式化时间戳
function toDate($time, $format = 'Y-m-d H:i:s') {
	if (empty ( $time )) {
		return '';
	}
	$format = str_replace ( '#', ':', $format );
	return date ($format, $time );
}

//截取字符串
function toSubstr($str, $length, $start=0, $charset="utf-8", $suffix=true)
{
	if(function_exists("mb_substr"))
    {
       if ($suffix && strlen($str)> $length*3)
       {
          return mb_substr($str, $start, $length, $charset)."...";
       }
       else
       {
       	  return mb_substr($str, $start, $length, $charset);
       }
    }
    elseif(function_exists('iconv_substr')) 
    {
       if ($suffix && strlen($str)> $length*3)
       {
          return iconv_substr($str,$start,$length,$charset)."...";
       }
       else
       {
          return iconv_substr($str,$start,$length,$charset);
       }
    }
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $slice = join("",array_slice($match[0], $start, $length));
    if($suffix) return $slice."…";
    return $slice;
	
}

function pwdHash($str,$type='md5')
{
	$str = strtolower(trim($str));
	$encrypt_str = hash($type, $str);
	$one_str = substr($encrypt_str, 2,12);
	$two_str = substr($encrypt_str, 6,16);
	$three_str = substr($encrypt_str, 12,32);
	
	$encrypt_str_two = hash($type, $one_str.$three_str);
	$re_str = hash($type,$encrypt_str_two.$two_str.$three_str);
	return $re_str;
}


//获取IP地址
function get_client_ip() {
	if (getenv ( "HTTP_CLIENT_IP" ) && strcasecmp ( getenv ( "HTTP_CLIENT_IP" ), "unknown" ))
		$ip = getenv ( "HTTP_CLIENT_IP" );
	else if (getenv ( "HTTP_X_FORWARDED_FOR" ) && strcasecmp ( getenv ( "HTTP_X_FORWARDED_FOR" ), "unknown" ))
		$ip = getenv ( "HTTP_X_FORWARDED_FOR" );
	else if (getenv ( "REMOTE_ADDR" ) && strcasecmp ( getenv ( "REMOTE_ADDR" ), "unknown" ))
		$ip = getenv ( "REMOTE_ADDR" );
	else if (isset ( $_SERVER ['REMOTE_ADDR'] ) && $_SERVER ['REMOTE_ADDR'] && strcasecmp ( $_SERVER ['REMOTE_ADDR'], "unknown" ))
		$ip = $_SERVER ['REMOTE_ADDR'];
	else
		$ip = "unknown";
	return ($ip);
}

 ?>